var config = require("config");
var dialogManager = require("dialogManager");
cc.Class({
    
    extends: cc.Component,

    properties:()=>({
        bomb: cc.Node,
        hero_hp: {
            default: null,
            type: cc.ProgressBar
        },
        bgm1:cc.Node,
        bgm2:cc.Node,
        enemyGroup: {
            default: null,
            type: require('enemyGroup'),
        },
        hero: {
            default: null,
            type: require('hero'),
        }, 
        ufoGroup: {
            default: null,
            type: require('ufoGroup'),
        },
        bulletGroup: {
            default: null,
            type: require('bulletGroup'),
        },
        bulletGroup_bb: {
            default: null,
            type: require('bulletGroup_bb'),
        },
        bossGroup: {
            default: null,
            type: require('bossGroup'),
        },
        bossBulletGroup: {
            default: null,
            type: require('bossBulletGroup'),
        },
        scoreDisplay:cc.Label,
        bombNoDisplay:cc.Label,
        coinNoDisplay:cc.Label,
        record_bg:cc.Node,
        pauseNode: cc.Node,
        gameOverNode: cc.Node,
        heroOnrushAni: cc.Node,
        laserAni: cc.Node,//激光
        sprArrSpeed :{
            default:[],
            type:[cc.SpriteFrame],
        },
        imgSpeedUp : {
            default : null,
            type : cc.Node
        },
        //排名信息
        rankNode: cc.Node,
    }),

    onLoad: function () {
        config.loadImage(this.bgm1,"Space1","resources/image/");
        config.loadImage(this.bgm2,"Space1","resources/image/");
        config.loadImage(this.record_bg,"record_bg","resources/image/");

        this.pauseNode.active = false;
        this.gameOverNode.active = false;
        this.heroOnrushAni.active = false;
        this.laserAni.active = false;

        //排名信息
        this.rankHead = this.rankNode.getChildByName("rank_head").getComponent(cc.Sprite);
        this.rankNum = this.rankNode.getChildByName("LabelAtlas_rank").getComponent(cc.Label);
        this.rankUp = this.rankNode.getChildByName("rank_up");
        this.rankNode.opacity = 0;
        if(typeof(wx)=="undefined"){
            this.rankHead.enabled = false;
        }
        
        //1倍速度
        this.imgSpeedUp.getComponent(cc.Sprite).spriteFrame = this.sprArrSpeed[0];

        //复活点击
        this.canFuhuoClick = true;
    
        this.score = 0;
        this.bombNo = 0;
        this.coinNo = 0;
        this.scoreDisplay.string = this.score;
        this.bombNoDisplay.string = this.bombNo;
        this.coinNoDisplay.string = this.coinNo;
        this.eState = D.commonInfo.gameState.start;
        //英雄血量
        this.heroHpNum = config.HeroMaxHp;
        //里程碑
        this.record_bg.active = false;
        this.record_num = this.record_bg.getChildByName('LabelAtlas_fuhuo').getComponent(cc.Label);
        this.record_m = this.record_bg.getChildByName('fuhuo_m').getComponent(cc.Sprite);
        //激光炮数量
        this.bombNoLabel = this.bomb.getChildByName('LabelAtlas_prop').getComponent(cc.Label);

        this.enemyGroup.startAction();
        this.bulletGroup.startAction();
        this.ufoGroup.startAction();
        //宝宝子弹
        if(config.CurPetIndex == -1){
        }else{
            this.bulletGroup_bb.startAction();
        }
        
        this.bomb.on('touchstart',this.bombOnclick,this);
        this.setHeroHp(this.heroHpNum);

        //背景图移动
        this.speed=500;
        this.accel=-2560;
        this.mapcamreoY=0;
        this.recordbgY=0;
        //计数器
        this.countNum = 0;
        this.isExitBoss = false;
        //初始化怪物数据
        //怪物血量和攻击 每100/200米跟新一次
        var hpIndex = Math.floor((this.score+config.MaxRecordMi)/100);
        var hitIndex = Math.floor((this.score+config.MaxRecordMi)/200);
        config.EnemyMaxHp = 100+hpIndex*100;
        config.EnemyHit = 100+hitIndex*100;
        cc.vv.audioMgr.playBGM("background1");


        //test
        this.bossBulletGroup.startAction();
        this.removeBossBullet();
        this.bossBulletGroup.pauseAction();
        // this.showBoss();
        // this.onDrag();

        //广告点击回掉
        var self = this;
        AppDelegate.javaCallJs = function(){
            console.log(" javaCallJs 广告点击回掉");
            self.fuhuoEnter();
        }

        if (cc.sys.OS_ANDROID == cc.sys.os && config.Publish == "android"){
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity","closeBanner","()V");
        } 
    },
    showBoss(){
        this.removeEnemy();
        this.enemyGroup.pauseAction();
        this.bossGroup.startAction();

        this.bossBulletGroup.resumeAction();
        this.bossBulletGroup.autoChangeBullet();
        this.isExitBoss = true;
        config.isBossShow = true;
    },
    bossDie(){
        this.bossBulletGroup.stopChangeBullet();
        this.bossBulletGroup.pauseAction();
        this.removeBossBullet();
       
        this.enemyGroup.resumeAction();
        this.isExitBoss = false;
        config.isBossShow = false;
    },
    setHeroHp: function(hp){
        let _hp = hp/config.HeroMaxHp;
        this.hero_hp.progress = _hp;
    },
    showRecordBg(){
        this.record_bg.active = true;
        this.record_num.string = this.score.toString();
    },
    bombOnclick: function(){
        // var bombNoLabel = this.bomb.getChildByName('LabelAtlas_prop').getComponent(cc.Label);
        var bombNo = parseInt(this.bombNoLabel.string);
        
        if (bombNo>0 && config.HeroState==0){
            this.bombNoLabel.string = bombNo-1;
            this.laserAniShow();
        } else {
            console.log('没有炸弹');
        }
    },
    //冲刺
    heroOnrush: function(){
        this.speed=5000;
        config.HeroState=1;
        config.ScoreTime=20;
        this.countNum = 0;
        this.hero.setHeroState(1);

        this.bulletGroup.stopAction();
        if(config.CurPetIndex == -1){
        }else{
            this.bulletGroup_bb.stopAction();
        }
        this.laserAni.active = false;
        this.heroOnrushAni.active = true;
        this.bomb.stopAllActions();
        var self = this;
        var delay = cc.delayTime(5);
        var callFunc = cc.callFunc(function(){
            self.speed=500;
            config.HeroState=0;
            config.ScoreTime=60;
            self.countNum = 0;
            self.hero.setHeroState(0);
            self.heroOnrushAni.active = false;

            if(config.doubleSpeed){
                self.speed=1000;
            }

            self.bulletGroup.changeBullet('ufoBullet');
            if(config.CurPetIndex == -1){
            }else{
                self.bulletGroup_bb.reStartAction();
            }
        });
        this.bomb.runAction(cc.sequence(delay,callFunc));
    },
    //冲击炮
    laserAniShow: function(){
        var self = this;
        this.laserAni.active = true;
        this.bomb.stopAllActions();
        var delay = cc.delayTime(3);
        var callFunc = cc.callFunc(function(){
            self.laserAni.active = false;
            self.bulletGroup.changeBullet('ufoBullet');
        });
        this.bomb.runAction(cc.sequence(delay,callFunc));
        this.bulletGroup.stopAction();
    },
    update: function (dt) {
        if(this.eState == D.commonInfo.gameState.pause){
            return;
        }
        if(this.speed==0){
            this.move=0;
        }else{
            var accelspeed=this.speed+dt*this.accel;
            this.move=(accelspeed*accelspeed-this.speed*this.speed)/(2*this.accel);
            //每次更新把初速度vo设为当前速度vt，实现加速效果
            // this.speed=accelspeed;
            this.mapcamreoY=this.mapcamreoY+this.move;
            this.bgm1.y=-1218-this.mapcamreoY;
            this.bgm2.y=1216-this.mapcamreoY;

            this.countNum++;
            if(this.countNum == config.ScoreTime){
                this.countNum = 0;
                this.gameScoreAdd(10);
            }

            if(this.bgm1.y < -3654){
                this.bgm1.y=-1218;
                this.mapcamreoY = 0;
            }
            if(this.bgm2.y < -3654){
                this.bgm2.y=1216;
            }

            //里程碑移动
            if(this.record_bg.active){
                this.recordbgY = this.recordbgY+this.move;
                this.record_bg.y=1050-this.recordbgY;
            }
            if(this.record_bg.y<-1450){
                this.recordbgY = 0;
                this.record_bg.y = 1050;
                this.record_bg.active = false;
            }

        }

    },
    //暂停按钮点击事件  
    pauseClick: function () {//暂停 继续
    
        if(this.eState == D.commonInfo.gameState.pause){
            // this.resumeAction();
            // this.eState = D.commonInfo.gameState.start;
        } else if(this.eState == D.commonInfo.gameState.start) {
            this.pauseNode.active = true;
            this.pauseAction();
            this.eState = D.commonInfo.gameState.pause;
        }
    },
    //游戏继续
    resumeAction: function(){
        if(this.isExitBoss){
            this.bossBulletGroup.resumeAction();
            this.bulletGroup.resumeAction();
            this.ufoGroup.resumeAction();
            this.hero.onDrag();
            // this.onDrag();
        }else{
            this.enemyGroup.resumeAction();
            this.bulletGroup.resumeAction();
            this.ufoGroup.resumeAction();
            this.hero.onDrag();
            // this.onDrag();
        }

        if(config.CurPetIndex == -1){
        }else{
            this.bulletGroup_bb.resumeAction();
        }
    },
    //游戏暂停
    pauseAction: function(){
        if(this.isExitBoss){
            console.log("boss存在 暂停")
            this.bossBulletGroup.pauseAction();
            this.bulletGroup.pauseAction();
            this.ufoGroup.pauseAction();  
            this.hero.offDrag();
        }else{
            this.enemyGroup.pauseAction();
            this.bulletGroup.pauseAction();
            this.hero.offDrag();
            this.ufoGroup.pauseAction();  
        }

        if(config.CurPetIndex == -1){
        }else{
            this.bulletGroup_bb.pauseAction();
        }
    },
    //增加分数
    gameScoreAdd: function (scoreno) {
        if(config.isBossShow){
            return;
        }
        this.score += scoreno;
        this.scoreDisplay.string = this.score.toString();
        if(this.score%1000 == 0 && this.score>config.MaxRecordMi){
            this.showRecordBg();
        }
        if(this.score%1000 == 0){
            this.showBoss();
        }
        //怪物血量和攻击 每100/200米跟新一次
        var hpIndex = Math.floor((this.score+config.MaxRecordMi)/100);
        var hitIndex = Math.floor((this.score+config.MaxRecordMi)/200);
        var initHp = 100;
        if(config.MaxRecordMi >= 2000){
            initHp = Math.floor(config.MaxRecordMi*100/2000);
        }
        config.EnemyMaxHp = 100+hpIndex*initHp;
        config.EnemyHit = 100+hitIndex*100;
        config.BossMaxHp = config.EnemyMaxHp*80;
        config.BossBulletHpDrop = config.EnemyMaxHp*40;


        //检测自己的排行
        if(this.score>=1000 && this.score%100 == 0){
            this.getUserRankInfo(this.score);
        }
    },
    //增加金币
    gameCoinAdd: function (coinno) {
        this.coinNo += coinno;
        this.coinNoDisplay.string = this.coinNo.toString();
    },
    //get分数
    getScore: function(){
        return parseInt(this.scoreDisplay.string);
    },
    //分数写到本地（ 当前分 最高分 历史记录）
    updateScore: function() {
        var currentScore = this.scoreDisplay.string;
        var scoreData = {
            'score':currentScore,
            'time': D.common.timeFmt(new Date(),'yyyy-MM-dd hh:mm:ss'),
        };
        var preData = cc.sys.localStorage.getItem('score');
        var preTopScore = cc.sys.localStorage.getItem('topScore');
        if (!preTopScore || parseInt(preTopScore) < parseInt(currentScore)){
           cc.sys.localStorage.setItem('topScore', currentScore); 
        }
        if(!preData){
            preData = [];
            preData.unshift(scoreData);
            
        } else {
            preData = JSON.parse(preData);
	    if (!(preData instanceof Array)){
                preData = [];    
            }
            preData.unshift(scoreData);
        }
        cc.sys.localStorage.setItem('currentScore', currentScore);
        cc.sys.localStorage.setItem('score', JSON.stringify(preData));
    },
    //炸弹清除怪物
    removeEnemy: function() {
        this.enemyGroup.node.removeAllChildren();
    },
    //清除boss子弹
    removeBossBullet: function() {
        this.bossBulletGroup.node.removeAllChildren();
    },
    //接到炸弹
    getUfoBomb: function() { 
        if (parseInt(this.bombNoDisplay.string)<3 && config.LaserNum<3){//多于三个炸弹就不累加
            this.bombNoDisplay.string += 1;
            config.LaserNum++;
        }   
    },
    //游戏结束
    gameOver: function(isDie){ 
        this.pauseAction();
        this.eState = D.commonInfo.gameState.pause;
        if(isDie){
            this.gameOverNode.active = true;
            config.HeroState = 2;

            if (cc.sys.OS_ANDROID == cc.sys.os && config.Publish == "android"){
                jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity","showInsert","()V");
            }
        }
            
    },
    //获取英雄位置
    getHeroPos(){
        return this.hero.getHeroPos();
    },
    //暂停界面(继续游戏)
    pauseGoonClick(){
        if(this.eState == D.commonInfo.gameState.pause){
            this.pauseNode.active = false;
            this.resumeAction();
            this.eState = D.commonInfo.gameState.start;
        } else if(this.eState == D.commonInfo.gameState.start) {
            // this.pauseAction();
            // this.eState = D.commonInfo.gameState.pause;
        }
    },
    pauseRestartClick(){
        cc.director.preloadScene("gameScene", function () {
            cc.director.loadScene("gameScene");
        });
    },
    pauseGohomeClick(){
        //显示结算界面
        var args = {}
        args.record_all = this.score;
        args.record_cur = this.score;
        args.gold_get = this.coinNo;
        args.KanShiPin = false;
        dialogManager.showGameResultDialog(args);
    },
    //复活按钮
    fuhuoEnterClick(){
        if(!this.canFuhuoClick)
            return;
        if (cc.sys.OS_ANDROID == cc.sys.os && config.Publish == "android"){
            jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity","showInsert","()V");
        }
        this.canFuhuoClick = false;
    },
    fuhuoEnter(){
        var self = this;
        var fuhuoFunc = function(){
            var fn = function(){
                self.fuhuo();
            }
            setTimeout(fn,1200);
            self.gameOverNode.active = false;
            self.hero.fuhuoAni();
        }
        // var args = {};
        // args.callFun = fuhuoFunc;
        // dialogManager.showShiPinDialog(args);
        fuhuoFunc();
        this.canFuhuoClick = true;
    },
    fuhuoCancelClick(){
        //显示结算界面
        var args = {}
        args.record_all = this.score;
        args.record_cur = this.score;
        args.gold_get = this.coinNo;
        args.KanShiPin = true;
        dialogManager.showGameResultDialog(args);
    },
    fuhuo(){
        this.resumeAction();
        this.eState = D.commonInfo.gameState.start;
        this.gameOverNode.active = false;
        this.heroHpNum = config.HeroMaxHp;
        this.setHeroHp(this.heroHpNum);
        config.LaserNum--;
        config.HeroState = 0;
    },
    //加速实现
    speedUpClick(){
        var self = this;
        if(config.HeroState != 0){
            return;
        }
        if(config.doubleSpeed){
            config.doubleSpeed = false; 
            this.countNum = 0;
            self.speed=500;
            config.ScoreTime=60;
            this.imgSpeedUp.getComponent(cc.Sprite).spriteFrame = this.sprArrSpeed[0];
        }else{
            config.doubleSpeed = true; 
            this.countNum = 0;
            self.speed=1000;
            config.ScoreTime=30;
            this.imgSpeedUp.getComponent(cc.Sprite).spriteFrame = this.sprArrSpeed[1];
        }

        var ret = {rank:10005}
        this.showRank(ret);
    },
    //获取用户排名
    getUserRankInfo(score){
        var self = this;
        var _url = "https://kg.51864.com/gemen/rank.php";
        var params = {};
        params.openid = config.weiXinCode;
        params.score = score;
        var fnRequest = function(){
            // console.log("sdk.youjoy.tv 正在连接服务器...");
            var xhr = cc.vv.http.sendRequest("",params,function(ret){
                console.log("ret = ",ret);
                self.showRank(ret);
            },_url);    
        };
        fnRequest();
    },
    showRank(ret){
        var rank = parseInt(ret.rank);
        if(rank<config.userRank || config.userRank == 0){
            config.userRank = rank;
            cc.vv.gameDataMgr.saveMyRank(rank);
        }else{
            return;
        }

        var self = this;
        this.rankNode.opacity = 255;
        this.rankNum.string = ret.rank;
        // this.rankUp 
        var delay = cc.delayTime(2);
        var callFunc = cc.callFunc(function(){
            self.hideRank();
        });
        this.rankNode.runAction(cc.sequence(delay,callFunc));

        this.rankUp.scale = 1;
        this.rankUp.y = 520;

        var jumpAction = cc.sequence(
        cc.spawn(
            cc.scaleTo(0.3, 0.2, 0.4),
            cc.moveBy(0.3, 0, 20)
        ),
        cc.spawn(
            cc.scaleTo(0.3,0.4, 0.6),
            cc.moveBy(0.3, 0, 20)
        ),
        cc.spawn(
            cc.scaleTo(0.3, 0.6, 0.8),
            cc.moveBy(0.3, 0, 20)
        ),
        cc.spawn(
            cc.scaleTo(0.3, 0.8, 1.0),
            cc.moveBy(0.3, 0, 20)
        ),
        cc.spawn(
            cc.scaleTo(0.3, 1.0, 1.2),
            cc.moveBy(0.3, 0, 20)
        )
        ).speed(2);
        this.rankUp.runAction(jumpAction);

    },
    hideRank(){
        this.rankNode.opacity = 0;
    }
});
